import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import store from "@/store";
Vue.use(VueRouter);
const oldPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (
	location,
	onComplete = () => {},
	onAbort = () => {}
) {
	oldPush.call(this, location, onComplete, onAbort);
};
const router = new VueRouter({
	mode: "history",
	routes,
	
 //控制路由切换的时候,滚动条的位置
 scrollBehavior() {
    return {
      x: 0,
      y: 0,
    };
  },
});

const whitePath = [
	"login",
	"home",
	"register",
	"search",
	"detail",
	"addCartSuccess",
];
// 2.配置全局前置守卫
router.beforeEach(async (to, from, next) => {
	const token = store.state.user.token;
	if (token) {
		console.log(2);
		if (to.name === "login") {
			next("/home");
		} else {
			const isUserInfo = !!store.state.user.userInfo.nickName;
			// 如果有用户信息 直接放行
			if (isUserInfo) {
				next();
			} else {
				// 如果没有，去请求用户数据
			try {
                await store.dispatch("user/getUserInfo");
				// 一旦得到用户信息就放行
				next();
            } catch (e) {
                store.dispatch("user/resetToken")
                next('/login')
            }
			}
		}
	} else {
		if (whitePath.includes(to.name)) {
			console.log(3);
			next(); //放行
		} else {
			next("/login");
		}
	}
});
export default router;
